$(function() {
	function valid_credit_card(value) {
		// accept only digits, dashes or spaces
		if (/[^0-9-\s]+/.test(value)) return false;
		 
		// The Luhn Algorithm. It's so pretty.
		var nCheck = 0, bEven = false;
		value = value.replace(/\D/g, "");
		 
		for (var n = value.length - 1; n >= 0; n--) {
		var cDigit = value.charAt(n),
		nDigit = parseInt(cDigit, 10);
		 
		if (bEven) {
		if ((nDigit *= 2) > 9) nDigit -= 9;
		}
		 
		nCheck += nDigit;
		bEven = !bEven;
		}
		 
		return (nCheck % 10) == 0;
		}
	$(document).ready(
			function() {

				$(":input").blur(
						function() {
							var myClasses = this.classList;
							var id = $(this).attr('id');
							if ($("#" + id).is(':visible')) {
								is_valid_field($(this).val(), myClasses[0],
										myClasses[1], id);
							}
						});
				$(document).submit(
						function() {
							var err = 0;
							$(":input").each(
									function(i) {

										var myClasses = this.classList;
										var id = $(this).attr('id');
										if ($("#" + id).is(':visible')) {
											err += is_valid_field(
													$(this).val(),
													myClasses[0], myClasses[1],
													id);
										}

									});
							// alert(err);
							if (err > 0) {
								return false;
							}
						});

			});

	function is_valid_field(value, required, optional, id) {
		$this = $("#" + id);
		var n = $this.val().length;
		var error = 0;
		if (required == "required") {
			if (n <= 0) {
				error += 1;
			}
			if (optional == "numeric") {
				if (isNaN($this.val())) {
					error += 1;
				}
			} else if (optional == "mobile") {
				var intRegex = /^\d+$/;
				if (!intRegex.test($this.val()) || n != 10) {
					error += 1;
				}
			} else if (optional == "email") {
				var emailRegex = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
				if (!emailRegex.test($this.val())) {
					error += 1;
				}
			} else if (optional == "password") {
				var passwordRegex = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20}/;
				if (!passwordRegex.test($this.val())) {
					error += 1;
				}
			} else if (optional == "card") {
				
				if (!valid_credit_card($this.val())) {
					error += 1;
				}
			}

		}
		if (error > 0) {
			if (!$this.closest(".control-group").hasClass("jerror"))
				$this.closest(".control-group").addClass("jerror");
			$this.siblings(".help-inline").css("display", "block");
			
			return error;
		} else {
			if ($this.closest(".control-group").hasClass("jerror"))
				$this.closest(".control-group").removeClass("jerror");
			$this.siblings(".help-inline").css("display", "none");
			return error;
		}
	}

});
